package com.wgo.bpot.common.transport.servicefacade.hessian;


import java.io.IOException;
import java.util.logging.Logger;

import com.caucho.hessian.io.AbstractDeserializer;
import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.AbstractSerializer;
import com.caucho.hessian.io.AbstractSerializerFactory;
import com.caucho.hessian.io.Deserializer;
import com.caucho.hessian.io.Serializer;
import com.wgo.bpot.common.transport.util.Assert;

/**
 * @author petterei
 */
public class FloatSerializerFactory extends AbstractSerializerFactory {
	private static final transient Logger log = Logger.getLogger(FloatSerializerFactory.class.getName());
	@Override
	public Serializer getSerializer(Class cls) {
//		log.info("Looking up serializer for: " + cls.getName());
		if (Float.class.isAssignableFrom(cls) || float.class.isAssignableFrom(cls)) {
			log.info("Returning float serializer for class: " + cls.getName());
			return new FloatSerializer();
		}
		return null;
	}
	@Override
	public Deserializer getDeserializer(Class cls) {
//		log.info("Looking up deserializer for: " + cls.getName());
		if (Float.class.isAssignableFrom(cls) || float.class.isAssignableFrom(cls)) {
			log.info("Returning float deserializer for class: " + cls.getName());
			return new FloatDeserializer();
		}
		return null;
	}
}
class FloatDeserializer extends AbstractDeserializer {
	@SuppressWarnings("unchecked")
	@Override
	public Object readMap(AbstractHessianInput in) throws IOException {
		String value = null;
		while (!in.isEnd()) {
			value = in.readString();
		}
		in.readMapEnd();
		Assert.assertNotNull(value, "Float deserializer: Expected Float value as string");

		Float floatValue = null;
		try {
			floatValue = new Float(value);
		} catch (NumberFormatException e) {
			throw new IOException("Expected Float type.");
		}
		return floatValue;
	}
}
class FloatSerializer extends AbstractSerializer {
	private static final transient Logger log = Logger.getLogger(FloatSerializer.class.getName());
	@Override
	public void writeObject(Object obj, AbstractHessianOutput out) throws IOException {
		String floatAsString = obj.toString();
		out.writeMapBegin(floatAsString);
		out.writeString(floatAsString);
		out.writeMapEnd();
	}
}